package com.breaktian.assemble.socket.tcp;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.util.Log;

import com.breaktian.assemble.socket.callback.ListenTcpCallBack;
import com.breaktian.assemble.socket.util.Utils;

public class TcpServerSocketTwo {

	private ServerSocket tcpServerSocket;
	private DataOutputStream dos;
	private DataInputStream dis;
	private Socket socket;
	private TcpStateListener mTcpStateListener;
	private int mPort = 0;
	
	public TcpServerSocketTwo(int port){
		mPort = port;
		try {
			tcpServerSocket = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
	 * 监听连接和消息
	 * */
	public void listen(final ListenTcpCallBack call){
		if(tcpServerSocket==null || call==null){
			return;
		}

		try {
			Log.d("TcpServerSocketTwo","等待客户端连接 <<<<<<<<................");
			socket = tcpServerSocket.accept();			
			new Thread(){
				public void run(){
					if(mTcpStateListener != null && socket != null && socket.isConnected()){						
						mTcpStateListener.onTCPConnected();  //回调上层连接状态
					}
				}
			}.start();
			while(true){				
				dos = new DataOutputStream(socket.getOutputStream());
				dis = new DataInputStream(socket.getInputStream());
				final String recvData = dis.readUTF();   //这个方法需要ios端实现writeUTF ，java正常
		
//				byte[] lendth = new byte[2];
//				dis.read(lendth,0,2);   //读取两个字节					
//				int len = byteArrayToInt(lendth);
//				byte[] data = new byte[len];
//				dis.read(data);
//				String srt = new String(data,"UTF-8");
//				String recvData = srt.trim();

				Log.d("TcpServerSocketTwo","serverSocket callback<<<<<<<<"+recvData);
				if(!"".equals(recvData) ){
					new Thread(){
						public void run(){
							call.onRecvUTFNoBack(recvData);
						}
					}.start();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			Log.d("TcpServerSocketTwo","IOException##################################################1");
			try {
				if(!tcpServerSocket.isClosed()){
					tcpServerSocket.close();
				}
			} catch (IOException ie) {
				e.printStackTrace();
			}
			
			new Thread(){
				public void run(){
					if(mTcpStateListener!=null){
						mTcpStateListener.onDisconnect();  //回调上层连接状态
					}
				}
			}.start();
			
			
			//listen(call);
		}
		
	}
	
	public static int byteArrayToInt(byte[] bytes) {
	       int value= 0;
	       //由高位到低位
	       for (int i = 0; i < 2; i++) {
	           int shift= (2 - 1 - i) * 8;
	           value +=(bytes[i] & 0x000000FF) << shift;//往高位游
	       }
	       return value;
	 }
	
	/**
	 * 发送数据 64kb以下
	 * 有返回数据
	 * */
	public void send(final String s){
		if(dos==null || socket == null) {
			return;
		}
		new Thread(){
			public void run(){
				try {
				//System.out.println("server发送数据："+s);
				dos = new DataOutputStream(socket.getOutputStream());
				dos.writeUTF(s);
				//System.out.println("server发送数据完毕");
				Log.d("TcpServerSocketTwo", "server发送数据完毕>>>"+s);
				} catch (IOException e) {
					e.printStackTrace();
					Log.d("TcpServerSocketTwo","IOException##################################################2");
				}
			}
		}.start();
						
		
	}
	
	
	
	public void setTcpStateListener(TcpStateListener tcpStateListener){
		mTcpStateListener = tcpStateListener;
	}
	
	
	
	/**
	 * 关闭socket
	 * */
	public void shutDown(){
		//Utils.log("关闭服务器");
		if(tcpServerSocket==null){
			return;
		}
		try {
			//Utils.log("退出循环监听连接");			
			tcpServerSocket.close();	
			if(socket!=null){
				socket.close();
			}
			Utils.log("close tcpServerSocket");
		} catch (IOException e) {
			Utils.log("shutDown出现异常："+e.getMessage());
			e.printStackTrace();
		}
	}
	
	
	

}
